package com.veer.shop.service.impl.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.veer.shop.mapper.MaterialCategoryMapper;
import com.veer.shop.param.MaterialCategoryParam;
import com.veer.shop.pojo.MaterialCategory;
import com.veer.shop.pojo.ResponseData;
import com.veer.shop.pojo.ValidResult;
import com.veer.shop.service.admin.MaterialCategoryService;
import com.veer.shop.utils.InitUtil;
import com.veer.shop.utils.ResponseUtil;

/**
 * 系统素材分类管理业务类
 * 
 * @author WangBin
 * 2020年10月6日-下午12:48:47
 */
@Service
public class MaterialCategoryServiceImpl implements MaterialCategoryService{
	
	@Autowired
	MaterialCategoryMapper materialCategoryMapper;
	
	/**
	 * 删除素材分类
	 */
	@Override
	public ResponseData<?> delete(String categoryId) {
		// TODO Auto-generated method stub
		String[] categoryIds = categoryId.split(",");
		
		for(String id : categoryIds)
		{
			materialCategoryMapper.delete(Integer.parseInt(id));
		}
		
		return ResponseUtil.success();
	}
	
	/**
	 * 素材分类详情
	 */
	@Override
	public ResponseData<?> get(Integer categoryId) {
		// TODO Auto-generated method stub
		MaterialCategory materialCategory = materialCategoryMapper.getById(categoryId);
		
		if(materialCategory.getCategoryId() == null)return ResponseUtil.error("素材分类不存在！");
		
		return ResponseUtil.success(materialCategory);
	}
	
	/**
	 * 素材列表分类
	 */
	@Override
	public ResponseData<?> getList(MaterialCategoryParam param, int pageNo, int pageSize) {
		PageMethod.startPage(pageNo, pageSize);
		List<MaterialCategory> categorys = materialCategoryMapper.getList(param);
		PageInfo pageInfo = new PageInfo(categorys);
		return ResponseUtil.success(ResponseUtil.getResponseList(pageInfo.getTotal(), categorys));
	}
	
	/**
	 * 新增|更新素材分类
	 */
	@Override
	public ResponseData<?> update(MaterialCategory category) {
		// 校验参数
		ValidResult validResult = validMaterial(category);
		
		if(validResult.getCode() == -1) {
			return ResponseUtil.error(validResult.getMessage());
		}
		
		int count = 0;
		if(StringUtils.isEmpty(category.getCategoryId())) {
			// 新增
			count = materialCategoryMapper.insert(category);
		} else {
			// 修改
			count = materialCategoryMapper.update(category);
		}
		
		if(count > 0) {
			return ResponseUtil.success();
		}
		
		return ResponseUtil.error();
	}
	
	/**
	 * 校验参数
	 * @param materialCategory
	 * @return
	 */
	public ValidResult validMaterial(MaterialCategory materialCategory) {
		ValidResult result = InitUtil.initFaildMap();
		
		if(StringUtils.isEmpty(materialCategory.getCategoryName())) {
			result.setMessage("分类名不可为空！");
			return result;
		}
		
		return InitUtil.initSuccMap();
	}
}
